package rsj.dao;

import com.rlyy.aibase.utils.base.MapNode;
import com.rlyy.aibase.utils.base.Node;
import com.rlyy.aibase.utils.base.TableNode;
import common.util.Assert;
import common.util.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import rsj.db.PostgreExecutor;
import rsj.db.SimpleSQLHolder;
import rsj.db.dbutils.UniqueID;
import rsj.domain.ProductPageQuery;
import rsj.table.DEL_STATUS;
import rsj.table.SYS_PROD;
import rsj.util.PaginationData;

import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class ProductDao extends BaseDao {

    private static final String table_name = "sys.sys_prod"; // 表名
    private static final String all_columns =
            "prod_id,prod_uid,prod_name,Prod_Type_Fid,Prod_Type_Sid,prod_status,prod_icon,prod_hpage" +
                    ",prod_overview,prod_addr,prod_callmethod,prod_encoding" +
                    ",prod_datasig,prod_response,prod_quest,prod_paramin" +
                    ",prod_paramout,prod_rexamle,prod_price,prod_description" +
                    ",prod_ctime,prod_endtime,prod_docname,prod_docid" +
                    ",prod_seq,sys_prty.prty_fname as prty_fname,sys_prty.prty_fname as prty_fname ";
    private static final String id = "prod_id";
    private static final String sectionInsertColumns = "";

    private static final ProductDao instance = new ProductDao();

    public static ProductDao getInstance() {
        return instance;
    }

    public MapNode getById(String prodId) {
        return getById(prodId, null);
    }

    public MapNode getById(String prodId, String orgId) {
        return (MapNode) PostgreExecutor.invokeSql(conn -> {

            if (StringUtils.isNotBlank(orgId)) {
                String sql = String.format(selectWithoutWhere, all_columns + ",sys_prty.prty_fname,sys_prty.prty_sname,pro.prod_status, " +
                                "CASE WHEN sys_prco.prco_collect is NULL THEN '0' ELSE sys_prco.prco_collect END ," +
//                                "CASE WHEN sys_status.sta_status is NULL THEN '50' ELSE sys_status.sta_status END ," +
                                " sys_status.sta_status ," +
                                "pro.prod_sales,pro.prod_utime"
                        , " sys.sys_prod pro left JOIN sys.sys_prty as sys_prty on sys_prty.prty_sid = pro.prod_type_sid "
                                + " LEFT JOIN (SELECT * from sys.sys_prco as prco %s ) as sys_prco ON sys_prco.prco_prod_id = pro.prod_id"
                                + " %s "
                                + " where prod_id = ?");

                sql = String.format(sql, " WHERE prco.prco_org_id = ? ", " LEFT JOIN ( select * from sys.sys_status WHERE sta_org_id = ?) " +
                        " AS sys_status ON sys_status.sta_prod_id = pro.prod_id ");
                return getQueryRunner().queryLinkRow(conn, sql, orgId, orgId, prodId);
            } else {

                String sql = String.format(selectWithoutWhere, all_columns +
                                ",sys_prty.prty_fname,sys_prty.prty_sname as prty_sname,pro.prod_status" +
                                ", CASE WHEN sys_prco.prco_collect is NULL THEN '0' ELSE sys_prco.prco_collect END " +
                                ",pro.prod_sales,pro.prod_utime"
                        , "sys.sys_prod pro left JOIN sys.sys_prty as sys_prty on sys_prty.prty_sid = pro.prod_type_sid "
                                + " LEFT JOIN (SELECT * from sys.sys_prco as prco %s ) as sys_prco ON sys_prco.prco_prod_id = pro.prod_id"
                                + " where prod_id = ?");

                sql = String.format(sql, "");
                return getQueryRunner().queryLinkRow(conn, sql, prodId);
            }

        });
    }

    public TableNode getHomePageData(String orgId) {
        return (TableNode) PostgreExecutor.invokeSql(conn -> {

            // sql
            String field = "prod.prod_id,prod.prod_name,prod.prod_type_sid,prty.prty_sname,prod.prod_status,prod.prod_icon,prco.prco_id,prodOrg.orgp_status";
            // SELECT prod.prod_id,prod.prod_name,prod.prod_type_sid,prty.prty_sname,prod.prod_status,prod.prod_icon,prod.prod_seq,prco.prco_id FROM sys.sys_prod AS prod LEFT JOIN sys.sys_orgp prodOrg ON prod.prod_id = prodOrg.orgp_prod_id LEFT JOIN (select * FROM sys.sys_prco prc WHERE prc.prco_collect = '0') prco ON prod.prod_id = prco.prco_prod_id AND prodOrg.orgp_id = '01' LEFT JOIN sys.sys_prty prty ON prod.prod_type_sid = prty.prty_sid where prod.prod_hpage = '0' AND prod.prod_status = '0' ORDER BY prod.prod_seq DESC
            String sql = "SELECT " +
                    " prod.prod_id,prod.prod_name,prod.prod_type_sid,prod.prty_sname,prod.prod_status,prod.prod_icon" +
//                    ",CASE WHEN sys_status.sta_status IS NULL THEN '50' ELSE sys_status.sta_status END" +
                    ",sys_status.sta_status " +
                    ",prod.prod_seq " +
                    "FROM " +
                    " ( SELECT prod.prod_id,prod.prod_name,prod.prod_type_sid,prty.prty_sname,prod.prod_status,prod.prod_icon,prod.prod_hpage,prod.prod_seq FROM sys.sys_prod AS prod LEFT JOIN sys.sys_prty prty ON prod.prod_type_sid = prty.prty_sid ) AS prod " +
                    " LEFT JOIN ( SELECT * FROM sys.sys_status sys_statu %s ) sys_status ON prod.prod_id = sys_status.sta_prod_id  " +
                    "WHERE " +
                    " prod.prod_hpage = '%s'  " +
                    " AND prod.prod_status = '%s'  " +
                    "ORDER BY " +
                    " prod.prod_seq ASC";

//            StringBuilder sql = new StringBuilder("SELECT ").append(field).append(" FROM sys.sys_prod AS prod " +
//                    "LEFT JOIN sys.sys_orgp prodOrg ON prod.prod_id = prodOrg.orgp_prod_id " +
//                    "LEFT JOIN sys.sys_prty prty ON prod.prod_type_sid = prty.prty_sid  " +
//                    "WHERE prod.prod_hpage = '0'  AND prod.prod_status = '0'  ORDER BY prod.prod_seq DESC ");

//            if (StringUtils.isBlank(orgId)) {// 没有机构id
//                final String finalSql = String.format(sql.toString(), "", DEL_STATUS.YES, DEL_STATUS.YES);
//                return getQueryRunner().queryLinkTableNode(conn, finalSql);
//            } else {// 有机构id
                final String finalSql = String.format(sql.toString(), " WHERE sys_statu.sta_org_id = ? ", DEL_STATUS.YES, DEL_STATUS.YES);
                return getQueryRunner().queryLinkTableNode(conn, finalSql, orgId);
//            }
        });
    }

    private StringBuilder createWhereCond(ProductPageQuery query, List<String> params) {
        StringBuilder whereCond = new StringBuilder("");
        if (StringUtils.isNotBlank(query.getProdName())) {
            params.add("%" + query.getProdName() + "%");
            whereCond.append(" AND prod.prod_name like ? ");
        }

        if (StringUtils.isNotBlank(query.getProdType())) {
            params.add(query.getProdType());
            whereCond.append(" AND prod.prty_fid = ? ");
        }
        return whereCond;
    }

    /**
     * @param data
     * @return 主键ID
     */
    public String insertOrUpdate(MapNode data) {
        long id = CommonUtil.safeLong(data.getValue(SYS_PROD.Prod_Id));

        return (String) PostgreExecutor.invokeSql(conn -> {
            String prod_uid = data.getValue("Prod_Uid");

            String insertOrUpdateSql = null;
            Object[] parameters = getTableParameters(data);
            int num = 0;

            List<Object> para = null;
            if (id > 0) {// 更新
                assertNoHaveProdUid(conn, prod_uid, id);
                insertOrUpdateSql = generateUpdateSql(data);
                para = createUpdateParam(parameters, data);
                num = getQueryRunner().update(conn, insertOrUpdateSql, para.toArray());
                Assert.isNotTrue(num == 0, "没有对数据做改动！");
                return String.valueOf(id);
            } else {// 新增
                assertNoHaveProdUid(conn, prod_uid, 0);
                insertOrUpdateSql = String.format(SimpleSQLHolder.insertSql, SYS_PROD.table_name
                        , SYS_PROD.insert_row, "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,to_date(?,'YYYY-MM-dd'),to_date(?,'YYYY-MM-dd'),?,?,?,?,TO_TIMESTAMP(?, 'YYYY-MM-DD HH24:MI:SS'),?");
                para = createInsertPara(parameters, data);
                num = getQueryRunner().update(conn, insertOrUpdateSql, para.toArray());
                return String.valueOf(para.get(0));
            }
        });
    }

    /**
     * 新增编辑 保证UID唯一
     * 策略：
     * 新增      查询不存在同一UID
     * 编辑      前提：同一产品在数据库中UID可以一样
     * 过滤条件 -> 除了要编辑的产品UID == 数据库UID，不能存在其他产品同样UID
     *
     * @param conn
     * @param prod_uid
     * @param id
     * @throws RuntimeException 存在同样UID时 抛出异常
     */
    private void assertNoHaveProdUid(Connection conn, String prod_uid, long id) throws RuntimeException {
        String sqlQueryUid = "select count(1) from " + table_name + " where Prod_Uid = ?";
        Node node = null;
        if (id > 0) {
            sqlQueryUid += " and Prod_Id != ? ";
            node = getQueryRunner().queryLinkNode(conn, sqlQueryUid, prod_uid, String.valueOf(id));
        } else {
            node = getQueryRunner().queryLinkNode(conn, sqlQueryUid, prod_uid);
        }
        Assert.isTrue(node.valueInt() <= 0, "已存在同样都产品编号，请修改！！");
    }


    /**
     * 不包含 id的参数
     *
     * @param data
     */
    private Object[] getTableParameters(MapNode data) {
        // 22 个字段
        return new Object[]{
                data.getValueDef(SYS_PROD.Prod_Uid, ""),
                data.getValueDef(SYS_PROD.Prod_Name, ""),
                data.getValueDef(SYS_PROD.Prod_Type_Fid, ""),
                data.getValueDef(SYS_PROD.Prod_Type_Sid, ""),
                data.getValueIntDef(SYS_PROD.Prod_Status, 1),
                data.getValueDef(SYS_PROD.Prod_Icon, ""),
                data.getValueIntDef(SYS_PROD.Prod_Hpage, 1),
                data.getValueDef(SYS_PROD.Prod_Overview, ""),
                data.getValueDef(SYS_PROD.Prod_Addr, ""),
                data.getValueDef(SYS_PROD.Prod_Callmethod, ""),
                data.getValueDef(SYS_PROD.Prod_Encoding, ""),
                data.getValueDef(SYS_PROD.Prod_Datasig, ""),
                data.getValueDef(SYS_PROD.Prod_Response, ""),
                data.getValueDef(SYS_PROD.Prod_Quest, ""),
                data.getValueDef(SYS_PROD.Prod_Paramin, ""),
                data.getValueDef(SYS_PROD.Prod_Paramout, ""),
                data.getValueDef(SYS_PROD.Prod_Rexamle, ""),
                data.getValueDef(SYS_PROD.Prod_Price, ""),
                data.getValueDef(SYS_PROD.Prod_Description, ""),
                data.getValueDef(SYS_PROD.Prod_Ctime, ""),
                data.getValueDef(SYS_PROD.Prod_Endtime, ""),
                data.getValueDef(SYS_PROD.Prod_Docname, ""),
                data.getValueDef(SYS_PROD.Prod_Docid, ""),
                data.getValueDef(SYS_PROD.Prod_Test_Type, "")
        };
    }

    private String generateUpdateSql(MapNode data) {
        return "update sys.sys_prod set" +
                " Prod_Uid=?," +
                " Prod_Name=?," +
                " Prod_Type_Fid=?, Prod_Type_Sid=?," +
                " Prod_Status=?, Prod_Icon=?," +
                " Prod_Hpage=?, Prod_Overview=?, Prod_Addr=?," +
                " Prod_Callmethod=?, Prod_Encoding=?, Prod_Datasig=?," +
                " Prod_Response=?, Prod_Quest=?, Prod_Paramin=?, Prod_Paramout=?," +
                " Prod_Rexamle=?, Prod_Price=?, Prod_Description=?," +
                " Prod_Ctime=to_date(?,'YYYY-MM-dd'), Prod_Endtime=to_date(?,'YYYY-MM-dd')," +
                " Prod_Docname=?, Prod_Docid=?," +
                " Prod_Test_Type=?," +
                " Prod_Seq=?," +
                " prod_utime=to_date(?,'YYYY-MM-dd') " +
                " where prod_id=?;";
    }

    private List<Object> createInsertPara(Object[] parameters, MapNode data) {
//        long seq = getNewReq(data.getValueDef(SYS_PROD.Prod_Type_Sid, null)
//                , data.getValueDef(SYS_PROD.Prod_Hpage, null));
        List<Object> para = Arrays.asList(parameters);

        LinkedList<Object> arr = new LinkedList<>(para);
        arr.addFirst(UniqueID.generateId());
        arr.add(data.getValue(SYS_PROD.Prod_Seq));
        arr.add(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        arr.add(0);
        return arr;
    }

    private List<Object> createUpdateParam(Object[] parameters, MapNode data) {
        List<Object> para = Arrays.asList(parameters);

        LinkedList<Object> arr = new LinkedList<>(para);

//        arr.addFirst(data.getValueDef(SYS_PROD.Prod_Id, null));
        arr.add(data.getValue(SYS_PROD.Prod_Seq));
        arr.add(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        arr.add(data.getValueDef(SYS_PROD.Prod_Id, null));
        return arr;
    }

    public TableNode getProdClass() {
        return (TableNode) invokeSql(conn -> {
            String sql = "SELECT Prty_Fname,Prod_Type_Fid,Prod_Id,Prod_Name,Prod_Uid FROM sys.sys_prod prod " +
                    "LEFT JOIN sys.sys_prty prty ON prty.prty_fid = prod.prod_type_fid  " +
                    " GROUP BY prod.prod_id,Prod_Type_Fid,Prty_Fname";
            return getQueryRunner().queryLinkTableNode(conn, sql);
        });
    }

    public PaginationData<TableNode> getPageByQuery(ProductPageQuery query) {
        if (query.getIsAllQuery()) {
            return getPageAll(query);
        } else {
            return getQueryProd(query);
        }
    }

    public PaginationData<TableNode> getPageByOrgId(ProductPageQuery query) {
        final PaginationData<TableNode> paginationData = new PaginationData<>();
        return (PaginationData<TableNode>) invokeSql(conn -> {
            String orgId = query.getOrgId();
            String like = "";
            String prodType = "";
            if (StringUtils.isNotBlank(query.getProdName())) {
                like = " AND prod.prod_name like '%" + query.getProdName() + "%'";
            }
            String countSql = "select  count(*)  from sys.sys_prod prod ";
            if (StringUtils.isNotBlank(query.getProdType())) {
                countSql += "LEFT JOIN sys.sys_prty prty ON prod.prod_type_sid = prty.prty_sid";
                prodType = " AND prty.prty_fid = '" + query.getProdType() + "'";
            }

            String querySql =
//                    "SELECT  CASE WHEN sys_status.sta_status is NULL THEN '50' ELSE sys_status.sta_status END ,\n" +
                    "SELECT sys_status.sta_status,\n" +
                    "        CASE WHEN (SELECT sys_prco.prco_prod_id FROM sys.sys_prco WHERE prco_org_id = '" + orgId + "' AND sys_prco.prco_prod_id = prod.prod_id AND prco_collect = '1') is NULL THEN '0' ELSE '1' END prco_collect ,\n" +
                    "     prod.prod_id,prod.prod_status, prod.prod_seq, prod.prod_overview,prod.prod_name,\n" +
                    "       prod.prod_price, prod.prod_sales, to_char(prod.prod_utime,'yyyy-MM-dd') prod_utime, prod_ctime, prod_endtime, prod.prod_uid  FROM sys.sys_prod AS prod\n" +
                    "              LEFT JOIN sys.sys_status ON sys_status.sta_prod_id =\n" +
                    "      prod.prod_id AND sys_status.sta_org_id= '" + orgId + "' " +
                    "           LEFT JOIN sys.sys_prty prty ON prod.prod_type_sid = prty.prty_sid\n" +
                    "          WHERE prod.prod_status = '1'" + like + prodType + "  ORDER BY prod.prod_seq::int DESC LIMIT " + query.getLimit() + " OFFSET " +  query.getOffset();

            TableNode tableNode = getQueryRunner().queryLinkTableNode(conn, querySql);
            countSql = countSql + " WHERE prod.prod_status = '1' " + like + prodType ;
            Node node = getQueryRunner().queryLinkNode(conn, countSql);
            int count = node.valueInt();
            paginationData.setDataList(tableNode);
            paginationData.setTotalCount(count);
            return paginationData;
        });
    }


    public PaginationData<TableNode> getQueryProd(ProductPageQuery query) {
        PaginationData<TableNode> paginationData = new PaginationData<>();

        String fields = "prod.prod_id,prod.prod_name,prod.prod_status,prod.prod_overview,prod.prod_utime" +
                ",prod.prod_seq,prod.prty_fid,prod.prty_fname,prod.prty_sid,prod.prty_sname" +
                ",CASE WHEN prco.prco_collect is NULL THEN '0' ELSE prco.prco_collect END" +
                ",prod.prod_sales,prod.prod_price,to_char(prod.prod_utime,'yyyy-MM-dd') prod_utime , prod_ctime, prod_endtime, prod.prod_uid ";
        //String sqlTemp = "SELECT  %s  FROM " +
        //        " ( SELECT * FROM sys.sys_prod AS pro LEFT JOIN sys.sys_prty prty ON pro.prod_type_sid = prty.prty_sid ) AS prod " +
        //        " LEFT JOIN ( SELECT prc.prco_collect,prc.prco_prod_id FROM sys.sys_prco prc ) prco ON prod.prod_id = prco.prco_prod_id " +
        //        " %s " + // 有orgId时，添加产品状态字段
        //        " WHERE prod.prod_status = '1'  %s";// 添加产品过滤条件
        //
        String sqlTemp = "SELECT  %s  FROM " +
                " ( SELECT * FROM sys.sys_prod AS pro LEFT JOIN sys.sys_prty prty ON pro.prod_type_sid = prty.prty_sid ) AS prod " +
                " LEFT JOIN ( SELECT prc.prco_collect,prc.prco_prod_id FROM sys.sys_prco prc ) prco ON prod.prod_id = prco.prco_prod_id " +
                " %s " + // 有orgId时，添加产品状态字段
                " WHERE prod.prod_status = '1'  %s";// 添加产品过滤条件

        LinkedList<String> params = new LinkedList<>();
        if (StringUtils.isBlank(query.getOrgId())) {
            StringBuilder whereCond = createWhereCond(query, params);

            String sqlQuery = String.format(sqlTemp, fields, "", whereCond.toString())
                    + "ORDER BY prod.prod_seq DESC  LIMIT " + query.getLimit() + " OFFSET " + query.getOffset();
            String sqlCount = String.format(sqlTemp, "count(*)", "", whereCond.toString());

            return queryPaginate(paginationData, params, sqlQuery, sqlCount);
        } else {
            StringBuilder whereCond = createWhereCond(query, params);

            String sqlQuery = String.format(sqlTemp, fields + ",CASE WHEN sys_status.sta_status is NULL THEN '50' ELSE sys_status.sta_status END "
                    , " where prc.prco_org_id = ? ",
                    " left join (SELECT * FROM sys.sys_status where sta_org_id = ?) AS sys_status on sys_status.sta_prod_id = prod.prod_id "
                    , whereCond.toString())
                    + "ORDER BY prod.prod_seq DESC  LIMIT " + query.getLimit() + " OFFSET " + query.getOffset();
            String sqlCount = String.format(sqlTemp, "count(1)", " where prc.prco_org_id = ? "
                    , " left join (SELECT * FROM sys.sys_status where sta_org_id = ?) AS sys_status on sys_status.sta_prod_id = prod.prod_id "
                    , whereCond.toString());

            params.addFirst(query.getOrgId());
            params.addFirst(query.getOrgId());
            return queryPaginate(paginationData, params, sqlQuery, sqlCount);
        }
    }

    private PaginationData<TableNode> queryPaginate(PaginationData<TableNode> paginationData, LinkedList<String> params, String sqlQuery, String sqlCount) {
        return (PaginationData<TableNode>) invokeSql(conn -> {
            TableNode tableNode = getQueryRunner().queryLinkTableNode(conn, sqlQuery, params.toArray());
            Node countNode = getQueryRunner().queryLinkNode(conn, sqlCount, params.toArray());
            paginationData.setTotalCount(countNode.valueInt());
            paginationData.setDataList(tableNode);
            return paginationData;
        });
    }

    public PaginationData<TableNode> getPage(ProductPageQuery query) {
        final PaginationData<TableNode> paginationData = new PaginationData<>();
        return (PaginationData<TableNode>) invokeSql(conn -> {
            String fields = " prod.prod_id, prod.prod_name, prty.prty_sid, prty.prty_sname, prty.prty_fid" +
                    ", prty.prty_fname, prod.prod_status, prod.prod_seq, prod.prod_overview, prod.prod_price" +
                    ", to_char(prod.prod_utime,'yyyy-MM-dd') prod_utime, prod_ctime, prod_endtime, prod.prod_uid ";
            String like = "";
            String prodType = "";
            if (StringUtils.isNotBlank(query.getProdName())) {
                like = " AND prod.prod_name like '%" + query.getProdName() + "%'";
            }
            String countSql = "select  count(*)  from sys.sys_prod prod ";
            if (StringUtils.isNotBlank(query.getProdType())) {
                countSql +="LEFT JOIN sys.sys_prty prty ON prod.prod_type_sid = prty.prty_sid";
                prodType = " AND prty.prty_fid = '" + query.getProdType() + "'";
            }

            String where = " where prod.prod_status = '1' " + like + prodType;

            String sql = "SELECT " + fields + " FROM sys.sys_prod AS prod "
                    + " LEFT JOIN sys.sys_prty prty ON prod.prod_type_sid = prty.prty_sid"
                    + where + " ORDER BY prod.prod_seq DESC LIMIT " + query.getLimit() + " OFFSET " + query.getOffset();

            TableNode tableNode = getQueryRunner().queryLinkTableNode(conn, sql);

            countSql += where;
            //String countSql = String.format(selectWithoutWhere, " count(1) ", table_name);
            Node node = getQueryRunner().queryLinkNode(conn, countSql);
            int count = node.valueInt();

            paginationData.setDataList(tableNode);
            paginationData.setTotalCount(count);

            return paginationData;
        });
    }

    //
    private PaginationData<TableNode> getPageAll(ProductPageQuery query) {
        final PaginationData<TableNode> paginationData = new PaginationData<>();
        return (PaginationData<TableNode>) invokeSql(conn -> {
            String fields = " prod.prod_id, prod.prod_name, prty.prty_sid, prty.prty_sname, prty.prty_fid" +
                    ", prty.prty_fname, prod.prod_status, prod.prod_seq, prod.prod_overview, prod.prod_price" +
                    ", to_char(prod.prod_utime,'yyyy-MM-dd') prod_utime, prod_ctime, prod_endtime, prod.prod_uid ";
            String sql = String.format("SELECT %s FROM sys.sys_prod AS prod "
                            + " LEFT JOIN sys.sys_prty prty ON prod.prod_type_sid = prty.prty_sid"
                            + " where prod.prod_status = '1' "
                            + " ORDER BY prod.prod_seq DESC LIMIT ? OFFSET ?"
                    , fields);
            TableNode tableNode = getQueryRunner().queryLinkTableNode(conn, sql, query.getLimit(), query.getOffset());

            String countSql = String.format(selectWithoutWhere, " count(1) ", table_name);
            Node node = getQueryRunner().queryLinkNode(conn, countSql);
            int count = node.valueInt();

            paginationData.setDataList(tableNode);
            paginationData.setTotalCount(count);

            return paginationData;
        });
    }

    public int sectionUpdateProd(MapNode data) {
        return (int) invokeSql(conn -> {
            String Prod_Status = data.getValueDef(SYS_PROD.Prod_Status, "");
            String Prod_Name = data.getValueDef(SYS_PROD.Prod_Name, "");
            String Prod_Type_Sid = data.getValueDef(SYS_PROD.Prod_Type_Sid, "");
            String Prod_Ctime = data.getValueDef(SYS_PROD.Prod_Ctime, "");
            String Prod_Endtime = data.getValueDef(SYS_PROD.Prod_Endtime, "");
            long Prod_Seq = Long.parseLong(data.getValue(SYS_PROD.Prod_Seq));
            String Prod_Id = data.getValue(SYS_PROD.Prod_Id);

            String insSql = String.format(updateSql, table_name, " Prod_Status = ? " +
                            ",Prod_Name = ? ,Prod_Type_Sid = ? ,Prod_Ctime=to_date(?,'YYYY-MM-dd') " +
                            ",Prod_Endtime = to_date(?,'YYYY-MM-dd') ,Prod_Seq = ? ",
                    " prod_id = ? ");
            return getQueryRunner().update(conn, insSql, Prod_Status, Prod_Name, Prod_Type_Sid, Prod_Ctime
                    , Prod_Endtime, Prod_Seq, Prod_Id);
        });
    }

    public String getMaxSeq() {
        return (String) invokeSql(conn -> {
            Node node = getQueryRunner().queryLinkNode(conn, " select max(to_number(prod_seq, '99999999999')) from sys.sys_prod ");
            String value = node.value();
            return StringUtils.isBlank(value) ? "0" : value;
        });
    }


    public TableNode listByType(String type) {
        return (TableNode) invokeSql(conn -> getQueryRunner().queryLinkTableNode(conn, "SELECT prod_id ,prod_name,prod_addr " +
                "FROM sys.sys_prod WHERE prod_type_fid = '" + type + "'"));
    }
}
